/**
 * 
 */
package com.cugbmao.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * @author mac
 * 
 */
public class Searcher
{
	private final IndexReader	reader;

	public Searcher(final Directory dir) throws IOException
	{
		reader = DirectoryReader.open(dir);
	}

	public void close() throws IOException
	{
		reader.close();
	}

	public void search(final String q) throws IOException, ParseException
	{

		IndexSearcher is = new IndexSearcher(reader);
		QueryParser parser = new QueryParser(Version.LUCENE_43, "contents",
				new StandardAnalyzer(Version.LUCENE_43));
		Query query = parser.parse(q);

		long start = System.currentTimeMillis();
		TopDocs hits = is.search(query, 10);
		long end = System.currentTimeMillis();

		System.out.println("Found " + hits.totalHits + " document(s) (in "
				+ (end - start) + " milliseconds) that matched query '" + q
				+ "':");
		for (ScoreDoc scordDoc : hits.scoreDocs)
		{
			Document doc = is.doc(scordDoc.doc);
			System.out.println(doc.get("fullpath"));
		}
	}

	public static void main(final String[] args)
			throws IllegalArgumentException, IOException, ParseException
	{
		if (args.length != 2)
		{
			throw new IllegalArgumentException("Usage: java "
					+ Searcher.class.getName() + " <index dir> <query>");
		}

		String indexDir = args[0];
		String q = args[1];

		Directory dir = FSDirectory.open(new File(indexDir));
		Searcher searcher = new Searcher(dir);
		try
		{
			searcher.search(q);
		}
		finally
		{
			searcher.close();
		}
	}
}
